package com.yunbiao.ybbusstopplate.refactoring.ui.fengxian;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.widget.ArrayAdapter;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.bumptech.glide.Glide;
import com.example.library_hy_advert.system.Cache;
import com.github.gzuliyujiang.wheelview.contract.OnWheelChangedListener;
import com.github.gzuliyujiang.wheelview.widget.WheelView;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.base.BaseSettingFragment;
import com.yunbiao.ybbusstopplate.databinding.FragmentFengxianSettingBinding;
import com.yunbiao.ybbusstopplate.refactoring.Config;

import java.io.File;
import java.util.List;

public class FengxianSettingFragment extends BaseSettingFragment {
    private static final String TAG = "DalianShanghaiSettingFr";

    private FragmentFengxianSettingBinding binding;

    @Override
    public int getViewId() {
        return R.layout.fragment_fengxian_setting;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.bind(requireView());

        List<Config.DeviceType> deviceTypes = Config.DeviceType.list();
        ArrayAdapter<Config.DeviceType> devicesAdapter = new ArrayAdapter<>(requireContext(),R.layout.myspiner,deviceTypes);
        devicesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spDeviceType.setAdapter(devicesAdapter);
        Config.DeviceType deviceType = Config.getDeviceType();
        int deviceTypeIndex = deviceTypes.indexOf(deviceType);
        binding.spDeviceType.setSelection(deviceTypeIndex);

        binding.tvSaveDeviceType.setOnClickListener(v -> save());

        List<Config.Agreement> list = Config.Agreement.list();
        ArrayAdapter<Config.Agreement> adapter = new ArrayAdapter<>(requireContext(),R.layout.myspiner,list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spAgreement.setAdapter(adapter);
        Config.Agreement agreement = Config.getAgreement();
        int index = list.indexOf(agreement);
        binding.spAgreement.setSelection(index);

        binding.tvSaveAgreement.setOnClickListener(v -> save());


        setCompanyIcon(Cache.getString(Config.Key.COMPANY_ICON.name()));

        String companyName = Cache.getString(Config.Key.COMPANY_NAME.name());
        binding.edtCompanyName.setText(companyName);

        String phoneNumber = Cache.getString(Config.Key.PHONE_NUMBER.name());
        binding.edtPhoneNumber.setText(phoneNumber);

        String startStartEndTime = Cache.getString(Config.Key.START_START_END_TIME.name());
        int[] startInts = resolveTime(startStartEndTime);
        binding.nwvStartStartHours.setRange(0,23,1);
        binding.nwvStartStartHours.setDefaultValue(startInts[0]);
        binding.nwvStartStartMinutes.setRange(0,59,1);
        binding.nwvStartStartMinutes.setDefaultValue(startInts[1]);
        binding.nwvStartEndHours.setRange(0,23,1);
        binding.nwvStartEndHours.setDefaultValue(startInts[2]);
        binding.nwvStartEndMinutes.setRange(0,59,1);
        binding.nwvStartEndMinutes.setDefaultValue(startInts[3]);

        String endStartEndTime = Cache.getString(Config.Key.END_START_END_TIME.name());
        int[] endInts = resolveTime(endStartEndTime);
        binding.nwvEndStartHours.setRange(0,23,1);
        binding.nwvEndStartHours.setDefaultValue(endInts[0]);
        binding.nwvEndStartMinutes.setRange(0,59,1);
        binding.nwvEndStartMinutes.setDefaultValue(endInts[1]);
        binding.nwvEndEndHours.setRange(0,23,1);
        binding.nwvEndEndHours.setDefaultValue(endInts[2]);
        binding.nwvEndEndMinutes.setRange(0,59,1);
        binding.nwvEndEndMinutes.setDefaultValue(endInts[3]);

        binding.cvChangeCompanyIcon.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1111);
        });

        binding.edtCompanyName.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                Cache.setString(Config.Key.COMPANY_NAME.name(),text);
            }
        });
        binding.edtPhoneNumber.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                Cache.setString(Config.Key.PHONE_NUMBER.name(),text);
            }
        });

        binding.nwvStartStartHours.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(true);
            }
        });
        binding.nwvStartStartMinutes.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(true);
            }
        });
        binding.nwvStartEndHours.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(true);
            }
        });
        binding.nwvStartEndMinutes.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(true);
            }
        });

        binding.nwvEndStartHours.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(false);
            }
        });
        binding.nwvEndStartMinutes.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(false);
            }
        });
        binding.nwvEndEndHours.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(false);
            }
        });
        binding.nwvEndEndMinutes.setOnWheelChangedListener(new MyWheelChangedListener() {
            @Override
            public void onWheelSelected(WheelView view, int position) {
                saveTime(false);
            }
        });

        binding.tvClearCompanyIcon.setOnClickListener(v -> {
            Cache.remove(Config.Key.COMPANY_ICON.name());
            setCompanyIcon("");
            showToast("已清除");
        });
        binding.tvClearCompanyName.setOnClickListener(v -> {
            Cache.remove(Config.Key.COMPANY_NAME.name());
            binding.edtCompanyName.setText("");
            showToast("已清除");
        });
        binding.tvClearPhoneNumber.setOnClickListener(v -> {
            Cache.remove(Config.Key.PHONE_NUMBER.name());
            binding.edtPhoneNumber.setText("");
            showToast("已清除");
        });
        binding.tvClearStartStartEndTime.setOnClickListener(v -> {
            Cache.remove(Config.Key.START_START_END_TIME.name());
            binding.nwvStartStartHours.setDefaultValue(0);
            binding.nwvStartStartMinutes.setDefaultValue(0);
            binding.nwvStartEndHours.setDefaultValue(0);
            binding.nwvStartEndMinutes.setDefaultValue(0);
            showToast("已清除");
        });
        binding.tvClearEndStartEndTime.setOnClickListener(v -> {
            Cache.remove(Config.Key.END_START_END_TIME.name());
            binding.nwvEndStartHours.setDefaultValue(0);
            binding.nwvEndStartMinutes.setDefaultValue(0);
            binding.nwvEndEndHours.setDefaultValue(0);
            binding.nwvEndEndMinutes.setDefaultValue(0);
            showToast("已清除");
        });
        binding.tvClearAll.setOnClickListener(v -> {
            binding.tvClearCompanyIcon.performClick();
            binding.tvClearCompanyName.performClick();
            binding.tvClearPhoneNumber.performClick();
            binding.tvClearStartStartEndTime.performClick();
            binding.tvClearEndStartEndTime.performClick();
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1111 && resultCode == Activity.RESULT_OK) {
            Uri selectedImageUri = data.getData();
            File file = UriUtils.uri2File(selectedImageUri);
            if(file != null){
                Cache.setString(Config.Key.COMPANY_ICON.name(),file.getAbsolutePath());
                setCompanyIcon(file.getAbsolutePath());
            }
        }
    }

    private void save(){
        boolean isChanged = false;
        Config.DeviceType selectDeviceType = (Config.DeviceType) binding.spDeviceType.getSelectedItem();
        Config.DeviceType currDeviceType = Config.getDeviceType();
        if(selectDeviceType.ordinal() != currDeviceType.ordinal()){
            Config.setDeviceType(selectDeviceType);
            isChanged = true;
        }

        Config.Agreement selectAgreement = (Config.Agreement) binding.spAgreement.getSelectedItem();
        Config.Agreement currAgreement = Config.getAgreement();
        if(selectAgreement.ordinal() != currAgreement.ordinal()){
            Config.setAgreement(selectAgreement);
            isChanged = true;
        }

        showToast("已保存");

        if(isChanged){
            ProgressDialog progressDialog = new ProgressDialog(requireContext());
            progressDialog.setMessage("正在重启APP...");
            progressDialog.show();

            requireView().postDelayed(() -> {
                AppUtils.relaunchApp(true);
            },1500);
        }
    }

    private void setCompanyIcon(String companyIcon){
        if(!TextUtils.isEmpty(companyIcon)){
            Glide.with(binding.ivCompanyIcon).asBitmap().load(companyIcon).into(binding.ivCompanyIcon);
        } else {
            binding.ivCompanyIcon.setImageDrawable(null);
        }
    }

    private int[] resolveTime(String time){
        int[] ints = new int[4];
        try {

            if(!TextUtils.isEmpty(time)){
                String[] split = time.split("—");
                String start = split[0];
                String end = split[1];

                String[] startArray = start.split(":");
                ints[0] = Integer.parseInt(startArray[0]);
                ints[1] = Integer.parseInt(startArray[1]);

                String[] endArray = end.split(":");
                ints[2] = Integer.parseInt(endArray[0]);
                ints[3] = Integer.parseInt(endArray[1]);
            }
        } catch (Exception ignore){}
        return ints;
    }

    private void saveTime(boolean isStart){
        try {
            StringBuilder stringBuilder = new StringBuilder();
            if(isStart){
                int startStartHours = binding.nwvStartStartHours.getCurrentItem();
                int startStartMinutes = binding.nwvStartStartMinutes.getCurrentItem();
                int startEndHours = binding.nwvStartEndHours.getCurrentItem();
                int startEndMinutes = binding.nwvStartEndMinutes.getCurrentItem();
                stringBuilder
                        .append(startStartHours < 10 ? "0" : "").append(startStartHours)
                        .append(":")
                        .append(startStartMinutes < 10 ? "0" : "").append(startStartMinutes)
                        .append("—")
                        .append(startEndHours < 10 ? "0" : "").append(startEndHours)
                        .append(":")
                        .append(startEndMinutes < 10 ? "0" : "").append(startEndMinutes);
                Log.d(TAG, "saveTime: " + stringBuilder.toString());
                Cache.setString(Config.Key.START_START_END_TIME.name(),stringBuilder.toString());
            } else {
                int EndStartHours = binding.nwvEndStartHours.getCurrentItem();
                int EndStartMinutes = binding.nwvEndStartMinutes.getCurrentItem();
                int EndEndHours = binding.nwvEndEndHours.getCurrentItem();
                int EndEndMinutes = binding.nwvEndEndMinutes.getCurrentItem();
                stringBuilder
                        .append(EndStartHours < 10 ? "0" : "").append(EndStartHours)
                        .append(":")
                        .append(EndStartMinutes < 10 ? "0" : "").append(EndStartMinutes)
                        .append("—")
                        .append(EndEndHours < 10 ? "0" : "").append(EndEndHours)
                        .append(":")
                        .append(EndEndMinutes < 10 ? "0" : "").append(EndEndMinutes);
                Log.d(TAG, "saveTime: " + stringBuilder.toString());
                Cache.setString(Config.Key.END_START_END_TIME.name(),stringBuilder.toString());
            }
        } catch (Exception ignore){}
    }

    private void showToast(String text){
        ToastUtils.getDefaultMaker().setGravity(Gravity.CENTER,0,0).setDurationIsLong(false).show(text);
    }

    static abstract class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
    }
    static abstract class MyWheelChangedListener implements OnWheelChangedListener {
        @Override
        public void onWheelScrolled(WheelView view, int offset) {

        }

        @Override
        public void onWheelScrollStateChanged(WheelView view, int state) {

        }

        @Override
        public void onWheelLoopFinished(WheelView view) {

        }
    }
}
